package com.hand.wfive.activity.picker

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.provider.VoicemailContract.Status
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isInvisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.doris.media.picker.utils.MediaUtils
import com.doris.media.picker.utils.permission.MyPermissionsUtils
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.adapter.PickerFileAdapter
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.Params
import com.hand.wfive.entity.PickerFileModel
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.click.NoFastClickUtils
import com.hand.wfive.util.click.singleClick
import kotlinx.android.synthetic.main.activity_picker_file.*
import org.jetbrains.anko.startActivity
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.concurrent.thread

@SuppressLint("SetTextI18n")
class PickerFileActivity : BaseActivity() {
    var mPath: String? = null
    val data = ArrayList<PickerFileModel>()

    companion object {
        fun show(context: Context, type: String) {
            context.startActivity<PickerFileActivity>(Params.type to type)
        }
    }

    private var mPickerType = Params.pickerImage

    private var mPageIndex = 0
    private val mFileList = ArrayList<File>()
    private lateinit var mAdapter: PickerFileAdapter

    private var mFileLocation = App.getContext().locationPath
    private val mSdf = SimpleDateFormat("修改日期：yyyy-MM-dd  HH:mm", Locale.CHINA)

    private lateinit var mTurnPreview: ActivityResultLauncher<Intent>

    override fun getContentViewId() = R.layout.activity_picker_file

    override fun init() {
        mPickerType = intent.getStringExtra(Params.type) ?: mPickerType

        topBar.addLeftBackImageButton().singleClick { finish() }
        topBar.updateBottomSeparatorColor(Color.parseColor("#CCCCCC"))

        initUi()
        initUpdateLocation()
        btn_sure.singleClick {
            if (mPath != null) {
                when (mPickerType) {
                    Params.pickerImage ->
                        mTurnPreview.launch(
                            PreviewImageActivity.showIntent(
                                mContext,
                                mPath!!
                            )
                        )

                    Params.pickerPdf ->
                        mTurnPreview.launch(
                            PreviewPdfActivity.showIntent(
                                mContext,
                                mPath!!
                            )
                        )

                    Params.pickerWord ->
                        mTurnPreview.launch(
                            PreviewWordActivity.showIntent(
                                mContext,
                                mPath!!
                            )
                        )

                }
            }
        }
        mTurnPreview = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) finish()
        }

        mAdapter = PickerFileAdapter()
        mAdapter.setOnItemClickListener { _, _, position ->
            val model = mAdapter.getItem(position)
            model.select = !model.select

            for (m in data.indices) {
                if (m != position) {
                    data[m].select = false
                }
            }
            mAdapter.notifyDataSetChanged()
            show(model)
        }
        recycler_file.layoutManager = LinearLayoutManager(mContext)
        (recycler_file.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        recycler_file.adapter = mAdapter

        mAdapter.loadMoreModule.isEnableLoadMore = true
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            mPageIndex++
            loadData()
        }

        if (hasPermission()) loadData()
        else {
            loading_view.showNoPermission()
            loading_view.setBtnClickListener {
                if (NoFastClickUtils.isFastClick()) return@setBtnClickListener
                MyPermissionsUtils.requestPermissionsTurn(
                    this, "用于访问手机word/pdf/图片文件",
                    object : MyPermissionsUtils.HavePermissionListener {
                        override fun havePermission() {
                            loading_view.showLoading()
                            loadData()
                        }
                    }, Permission.MANAGE_EXTERNAL_STORAGE
                )
            }
        }
    }

    private fun show(model: PickerFileModel) {
        if (model.select) {
            mPath = model.path
            ll_action.visibility = View.VISIBLE
        } else {
            mPath = null
            ll_action.visibility = View.GONE
        }
    }

    private fun initUi() {
        when (mPickerType) {
            Params.pickerWord -> {
                topBar.setTitle("选择Word")
                qtv_local.text = "本地Word"
                qtv_album.isInvisible = true
            }

            Params.pickerPdf -> {
                topBar.setTitle("选择PDF")
                qtv_local.text = "本地PDF"
                qtv_album.isInvisible = true
            }

            else -> {
                topBar.setTitle("选择图片")
                qtv_local.text = "本地图片"
                qtv_album.isInvisible = false
            }
        }
    }

    private fun initUpdateLocation() {
        qtv_wechat.singleClick {
            mPageIndex = 0
            mFileLocation =
                if (mPickerType == Params.pickerImage) App.getContext().wechatImgPath
                else App.getContext().wechatFilePath
            refreshData()
        }
        qtv_local.singleClick {
            mPageIndex = 0
            mFileLocation = App.getContext().locationPath
            refreshData()
        }
        qtv_album.singleClick {
            mPageIndex = 0
            mFileLocation = App.getContext().dcimPath
            refreshData()
        }
    }

    private fun refreshData() {
        mAdapter.setNewInstance(arrayListOf())
        loading_view.showLoading()
        loadData()
    }

    private fun loadData() {
        if (mPickerType == Params.pickerImage) {
            loadImage()
        } else {
            loadFile()
        }
    }

    private fun loadImage() {
        MediaUtils.loadImage(
            this, folder = mFileLocation, pageIndex = mPageIndex
        ) {
            if (it.isEmpty()) {
                if (mPageIndex == 0) {
                    mAdapter.setNewInstance(arrayListOf())
                    loading_view.showTip("暂无图片")
                } else {
                    mAdapter.loadMoreModule.loadMoreEnd(true)
                }
            } else {
                val data = ArrayList<PickerFileModel>()
                it.forEach { media ->
                    val model = PickerFileModel()
                    model.name = media.name
                    model.path = media.path
                    model.time = mSdf.format(Date(media.lastModifed))
                    model.size = "文件大小：${media.sizeTransform}"
                    data.add(model)
                }
                if (mPageIndex == 0) {
                    loading_view.hide()
                    mAdapter.setNewInstance(data)
                } else {
                    mAdapter.addData(data)
                    mAdapter.loadMoreModule.loadMoreComplete()
                }
            }
        }
    }

    private fun loadFile() {
        thread {
            mFileList.clear()
//            loadFile(File(mFileLocation))

            var mFileLocation1 =
                if (mPickerType == Params.pickerImage) App.getContext().wechatImgPath
                else App.getContext().wechatFilePath
            var mFileLocation2 = App.getContext().locationPath

            loadFile(File(mFileLocation1))
            loadFile(File(mFileLocation2))
            mFileList.sortByDescending { it.lastModified() }

            mFileList.forEach {
                val model = PickerFileModel()
                model.type = mPickerType
                model.name = it.name
                model.path = it.path
                model.time = mSdf.format(Date(it.lastModified()))
                model.size = "文件大小：${FileUtils.convertFileSize(it.length())}"
                data.add(model)
            }
            runOnUiThread {
                loading_view.hide()
                mAdapter.setNewInstance(data)
                if (data.isEmpty()) {
                    if (mPickerType == Params.pickerWord) {
                        loading_view.showTip("暂无Word")
                    } else {
                        loading_view.showTip("暂无PDF")
                    }
                }
                mAdapter.loadMoreModule.loadMoreEnd(true)
            }
        }
    }

    private fun loadFile(file: File) {
        file.listFiles()?.forEach {
            val name = it.name
            if (!name.startsWith(".", true)) {
                if (it.isDirectory) {
                    if (!it.absolutePath.endsWith("Android")) {
                        loadFile(it)
                    }
                } else {
                    if (it.length() >= 512) {
                        if (mPickerType == Params.pickerWord && isWord(name)) {
                            mFileList.add(it)
                        } else if (mPickerType == Params.pickerPdf && isPdf(name)) {
                            mFileList.add(it)
                        }
                    }
                }
            }
        }
    }

    private fun isWord(name: String) = name.endsWith("doc", true)
            || name.endsWith("docx", true)

    private fun isPdf(name: String) = name.endsWith("pdf", true)

    private fun hasPermission() =
        XXPermissions.isGranted(mContext, Permission.MANAGE_EXTERNAL_STORAGE)

    override fun turnSystemPermissionBack() {
        super.turnSystemPermissionBack()
        if (hasPermission()) {
            loading_view.showLoading()
            loadData()
        }
    }
}